﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using EaseDapper.MySqlTest.XmlModel;

namespace EaseDapper.MySqlTest.ExecuteXML
{
    public class SerializerConfig
    {
        private static string ConfigFileName => string.Concat(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "config\\dapper.config.xml");
        public static void CreateConfigUtil()
        {
            if (File.Exists(ConfigFileName)) return;
            var equipment = new DapperConfig
            {
                Name = "Test",
                DataSource = GetDataSource()
            };
            var xml = new XmlSerializer(typeof(ConnectConfig));
            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);//不要命名空间
            using var writer = new StreamWriter(ConfigFileName);
            xml.Serialize(writer, equipment, ns);
        }

        public static DapperConfig ReadConfig()
        {
            if (!File.Exists(ConfigFileName))
            {
                CreateConfigUtil();
            };
            var fileStream = new FileStream(ConfigFileName, FileMode.Open);
            var xml = new XmlSerializer(typeof(ConnectConfig));
            DapperConfig config = xml.Deserialize(fileStream) as DapperConfig;
            return config;
        }

        private static DataSource GetDataSource()
        {
            return new DataSource()
            {
                dbtype = "MySQL",
                connstr = "Database=jx_equipment;Data Source=localhost;User Id=root;Password=root123456;CharSet=utf8;port=3306;SslMode=none;"
            };
        }
    }
}
